package com.fly.demo.service.impl;

import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.fly.core.utils.JsonBeanUtils;
import com.fly.core.utils.ShellExecutor;
import com.fly.demo.entity.Article;
import com.fly.demo.entity.BlogData;
import com.fly.demo.service.DataInitor;

import lombok.extern.slf4j.Slf4j;

/**
 * 通过WebApi接口初始化
 */
@Slf4j
@Order(1)
@Component
public class BlogApiDataInitor implements DataInitor
{
    @Override
    public boolean init(List<Article> articles)
    {
        try
        {
            // 容器运行，镜像需安装curl
            log.info("start init...");
            List<Article> list = IntStream.rangeClosed(1, 2)
                .mapToObj(i -> String.format("curl -e \"blog.csdn.net\" \"https://blog.csdn.net/community/home-api/v1/get-business-list?page=%s&size=100&businessType=blog&username=qq_16127313\"", i))
                .map(cmd -> ShellExecutor.execute(cmd))
                .map(json -> parseToArticles(json))
                .flatMap(List::stream)
                .collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(list))
            {
                articles.addAll(list);
            }
            return !CollectionUtils.isEmpty(articles);
        }
        catch (Exception e)
        {
            log.error(e.getMessage(), e);
            return false;
        }
    }
    
    /**
     * 解析json为List
     * 
     * @param json
     * @return
     */
    private static List<Article> parseToArticles(String json)
    {
        try
        {
            return JsonBeanUtils.jsonToBean(json, BlogData.class, true).getData().getList();
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
            return Collections.emptyList();
        }
    }
}